<template>
    <div class="container">
        <el-input v-model="input" style="width: 240px" placeholder="输入角色名称" />
        <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUser">查询</el-button>
        <el-button style="width: 6rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="newUser" v-if="hasPermission(authStore.permissions,32)" >新建角色</el-button>
        <!-- 点击新建角色打开 -->
        <el-dialog v-model="visible" :show-close="false" width="800">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div>新建/修改角色</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div style="display: flex; flex-direction: column; gap: 1rem; margin-top: 1rem;">
  <!-- 角色名称 -->
  <div style="display: flex; align-items: center;">
    <label class="label-text"><span style="color: red;">*</span>角色名称:</label>
    <div style="flex: 1;">
      <el-input
        v-model="userName"
        @input="roleNameError = false"
        :class="{ 'input-error': roleNameError }"
        style="width: 100%;"
      />
    </div>
  </div>
  <div v-if="roleNameError" class="error-text">角色名称不能为空</div>

  <!-- 备注信息 -->
  <div style="display: flex; align-items: center;">
    <label class="label-text">备注：</label>
    <el-input v-model="userMessage" style="width: 100%;" />
  </div>
</div>
      <div style="display: flex;margin-top: 2rem;">
        <el-button plain  :class="{ 'selected-tab': currentTab === 1 }" @click="currentTab = 1">告警管理</el-button>
        <el-button plain  :class="{ 'selected-tab': currentTab === 2 }" @click="currentTab = 2">智能巡检</el-button>
        <el-button plain  :class="{ 'selected-tab': currentTab === 3 }" @click="currentTab = 3">资源管理</el-button>
        <el-button plain  :class="{ 'selected-tab': currentTab === 4 }" @click="currentTab = 4">系统管理</el-button>
        </div>
        

    <div v-show="currentTab === 1">
        <el-tree
            style="max-width: 600px ;margin-top: 2rem;"
            :data="alarmManagement"
            show-checkbox
            node-key="id"
            default-expand-all
            ref="alarmTree"
  />
    </div>

    <div v-show="currentTab === 2">
        <el-tree
            style="max-width: 600px ;margin-top: 2rem;"
            :data="smartInspection"
            show-checkbox
            node-key="id"
            default-expand-all
            ref="inspectionTree"
  />
    </div>

    <div v-show="currentTab === 3">
        <el-tree
            style="max-width: 600px ;margin-top: 2rem;"
            :data="resourceManagement"
            show-checkbox
            node-key="id"
            default-expand-all
            ref="resourceTree"
  />
    </div>

    <div v-show="currentTab === 4">
        <el-tree
            style="max-width: 600px ;margin-top: 2rem;"
            :data="systemManagement"
            show-checkbox
            node-key="id"
            default-expand-all
            ref="systemTree"
  />
    </div>
      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sumbitMessage()">保存</el-button>
        </div>
      </div>
    </el-dialog>


    <el-table :data="displayedData" style="width: 80%; margin-top: 3rem;">
  <el-table-column label="序号" width="100">
    <template #default="{ row, $index }">
      <span v-if="row.role">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.roleName" label="角色名称" width="150">
    <template #default="{ row }">
      <span v-if="row.role" style="color: black;">{{ row.role.roleName }}</span>
      <span v-else style="color: transparent;">空</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.description" label="备注信息" width="250">
    <template #default="{ row }">
      <span v-if="row.role">{{ row.role.description }}</span>
      <span v-else style="color: transparent;">空</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.createTime" label="创建时间" width="200">
    <template #default="{ row }">
      <span v-if="row.role">{{ row.role.createTime }}</span>
      <span v-else style="color: transparent;">空</span>
    </template>
  </el-table-column>
  
  <el-table-column fixed="right" label="操作" min-width="200">
    <template #default="{ row }">
      <div v-if="row.role">
        <el-button link type="primary" size="small" @click="deleteTower(row)"  v-if="hasPermission(authStore.permissions,41)" style="color:#f56c6c;">删除</el-button>
        <el-button link type="primary" size="small" @click="changeRole(row)" v-if="hasPermission(authStore.permissions,40)" style="color: rgb(110, 78, 208);">修改</el-button>
      </div>
      <div v-else style="color: transparent;">无操作</div>
    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

    </div>

    
    <el-dialog v-model="deleteVisible" title="提示" width="500" center>
            <span>
              是否需要删除权限 "{{deleteItem.role.roleName}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible = false">取消</el-button>
              <el-button type="primary" @click="handleClick()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>
</template>

<script lang="ts" setup>
    import { CircleCloseFilled } from '@element-plus/icons-vue';
    import { ref ,onMounted ,nextTick ,onUnmounted} from 'vue'
    import request from '@/utils/request';
    import type { TreeInstance } from 'element-plus'; // 引入 el-tree 的类型
    import { useAuthStore } from '@/stores/user';
    import { hasPermission } from '@/utils/permissionUtils';
    import showMessage from '@/utils/showMessage';
    const roleNameError = ref(false);
    const authStore = useAuthStore()
    const tableData = ref([]); // 原始数据
    const displayedData = ref([]); // 当前页显示的数据
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页条数
    const total = ref(0); // 总条数
    const input = ref('')
    const userName = ref('')
    const userMessage = ref('')
    const visible = ref(false)
    const currentTab = ref(1)
    const flag = ref()//flag为1代表是新建，为2表示是修改
    // 新建角色
    const newUser= () => {
      roleNameError.value = false
      visible.value = true;
      flag.value = 1
      userName.value = ''
      userMessage.value = ''
      alarmTree.value = null
      inspectionTree.value = null
      resourceTree.value = null
      systemTree.value = null
    }

    const filterUser = () => {
      if (input.value) {
  
          const formData = new FormData();
          formData.append("roleName",input.value),
          request.post("/user/getRoleByRoleName",formData).then(
            (res)=>{
              if(res.status == 200){
                tableData.value = res.data
                updateDisplayedData();
            }
            }
          )
      }else {
        getAllRole()
      }
    }
    // 删除逻辑

    const deleteVisible = ref(false)
    const deleteItem = ref()
    const deleteTower = (row:any) => {
      deleteVisible.value = true
      deleteItem.value = row
    }
    const handleClick =() => {
        const formData = new FormData();
        formData.append("roleID",deleteItem.value.role.id),
        request.post("/user/deleteRoleByID",formData).then(
          (res)=>{
            showMessage(res);
            if(res.status == 200){
              // 获取所有用户信息
               // 删除角色
               request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"系统管理",
                operationResult:"成功删除角色信息",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              
              })
              getAllRole()
              deleteVisible.value = false
            }
          }
        )
    }
    // 修改逻辑
    const checkedIds = ref([]);//保存选中的权限数组
    const selectId = ref();//保存选中的id
    const changeRole = (row: any) => {
  // 提取权限数据
  checkedIds.value = row.permissions.map((item: any) => item.id);
  userName.value = row.role.roleName;
  userMessage.value = row.role.description;
  selectId.value = row.role.id;
  

  // 等待 DOM 更新后设置树的勾选状态
  const alarmData = row.permissions.filter((item: any) => item.firstDirectory === '告警管理').map((item: any) => item.id);
  const inspectionData = row.permissions.filter((item: any) => item.firstDirectory === '智能巡检').map((item: any) => item.id);
  const resourceData = row.permissions.filter((item: any) => item.firstDirectory === '资源管理').map((item: any) => item.id);
  const systemData = row.permissions.filter((item: any) => item.firstDirectory === '系统管理').map((item: any) => item.id);
  
 nextTick(() => {
    // 将权限数据传递给树组件
    setTimeout(() => {
      if (alarmTree.value) {
        alarmTree.value.setCheckedKeys(alarmData); // 更新告警管理勾选状态
      }

      if (inspectionTree.value) {
        inspectionTree.value.setCheckedKeys(inspectionData); // 更新智能巡检勾选状态
      }

      if (resourceTree.value) {
        resourceTree.value.setCheckedKeys(resourceData); // 更新资源管理勾选状态
      }

      if (systemTree.value) {
        systemTree.value.setCheckedKeys(systemData); // 更新系统管理勾选状态
      }
    }, 50); // 延迟 50 毫秒，确保树组件渲染完毕
  });

  visible.value = true;
  flag.value = 2;
};
// 引用树形组件
const alarmTree = ref<TreeInstance | null>(null);
const inspectionTree = ref<TreeInstance | null>(null);
const resourceTree = ref<TreeInstance | null>(null);
const systemTree = ref<TreeInstance | null>(null);
const sumbitMessage =() => {
  if (!userName.value.trim()) {
    roleNameError.value = true;
    return;
  }
  if(flag.value === 1) {
    const roleName = userName.value;
    const describe = userMessage.value;
      // 获取树形控件的勾选数据
    const alarmChecked = alarmTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const inspectionChecked = inspectionTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const resourceChecked = resourceTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const systemChecked = systemTree.value?.getCheckedNodes().map(node => node.id)  || [];
    //勾选三级菜单的时候，二级菜单，一级菜单显示就是undefined，所以需要过滤
    const allChecked = [...alarmChecked,...inspectionChecked,...resourceChecked,...systemChecked].filter(item => item != undefined)
    //调用接口上传数据库
    request.post('/user/insertPermission',{
      roleName,
      description:describe,
      permissionID:allChecked,
    }).then((res)=>{
      
      showMessage(res)
      if(res.status == 200) {
    

         // 创建角色
         request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"系统管理",
                operationResult:"创建角色成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
        
              })

        getAllRole()
        visible.value = false,
        alarmTree.value = null,
        inspectionTree.value =null, 
        resourceTree.value = null,
        systemTree.value = null,
        userName.value = '',
        userMessage.value = ''
      }
    })
  } else if (flag.value === 2 ) {
    const roleName = userName.value;
    const describe = userMessage.value;
    const alarmChecked = alarmTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const inspectionChecked = inspectionTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const resourceChecked = resourceTree.value?.getCheckedNodes().map(node => node.id)  || [];
    const systemChecked = systemTree.value?.getCheckedNodes().map(node => node.id)  || [];
    //勾选三级菜单的时候，二级菜单，一级菜单显示就是undefined，所以需要过滤
    const allChecked = [...alarmChecked,...inspectionChecked,...resourceChecked,...systemChecked].filter(item => item != undefined)
     
    //调用接口上传数据库
    request.post('/user/updatePermission',{
      roleID:selectId.value,
      roleName,
      description:describe,
      permissionID:allChecked,
    }).then((res)=>{
      showMessage(res);
      if(res.status == 200) {
      
         // 修改角色
         request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"系统管理",
                operationResult:"修改角色信息成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              
              })

        getAllRole()
        visible.value = false,
        alarmTree.value = null,
        inspectionTree.value =null, 
        resourceTree.value = null,
        systemTree.value = null,
        userName.value = '',
        userMessage.value = ''
      }
    })
  }
}
  // 获取全部的权限
  const permissions = ref<any>('')
  const alarmManagement = ref<any>('')//告警管理部分
  const smartInspection = ref<any>('')//智能巡检部分
  const resourceManagement = ref<any>('')//资源管理部分
  const systemManagement = ref<any>('')//系统管理部分
  const getAllPermission = () => {
    request.get('/user/getAllPermission').then((response)=>{
        // 这里就是获取所有的数据
        permissions.value = buildTree(response.data);
        // 按 firstDirectory 分组数据
        alarmManagement.value = response.data.filter((item:any) => item.firstDirectory === '告警管理');
        smartInspection.value = response.data.filter((item:any) => item.firstDirectory === '智能巡检');
        resourceManagement.value = response.data.filter((item:any) => item.firstDirectory === '资源管理');
        systemManagement.value = response.data.filter((item:any) => item.firstDirectory === '系统管理');

        // 分别构建每个分组的树形结构
        alarmManagement.value = buildTree(alarmManagement.value);
        smartInspection.value = buildTree(smartInspection.value);
        resourceManagement.value = buildTree(resourceManagement.value);
        systemManagement.value = buildTree(systemManagement.value);        
    })
  }

  // 将数据转换为树结构
const buildTree = (data:any)  => {
  const tree:any = [];

  data.forEach((item:any) => {
    let firstNode = tree.find((node:any) => node.label === item.firstDirectory);
    if (!firstNode) {
      firstNode = { label: item.firstDirectory, children: [] };
      tree.push(firstNode);
    }

    let secondNode = firstNode.children.find((node:any) => node.label === item.secondDirectory);
    if (!secondNode) {
      secondNode = { label: item.secondDirectory, children: [] };
      firstNode.children.push(secondNode);
    }

    if (item.thirdDirectory) {
      let thirdNode = secondNode.children.find((node:any) => node.label === item.thirdDirectory);
      if (!thirdNode) {
        thirdNode = { label: item.thirdDirectory, children: [] };
        secondNode.children.push(thirdNode);
      }

      thirdNode.children.push({ id: item.id, label: item.permissionName });
    } else {
      secondNode.children.push({ id: item.id, label: item.permissionName });
    }
  });

  return tree;
}


// 获取全部
const getAllRole = () => {
  request.get('/user/getAllRole').then(
    (res)=>{
      if(res.data){
        tableData.value = res.data
        total.value = res.data.length;
        updateDisplayedData();
      }
    }
  )
}

// 更新显示的数据
const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};
const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 10 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllRole()
    getAllPermission()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});

</script>

<style scoped>
.container {
    width: 100%;
    height: calc(100vh - 100px);
    display: block;
    padding: 20px;
    box-sizing: border-box;
}
.container-head {
    display: flex
} 
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.input-text {
    width: 20%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.input-text1 {
    width: 10%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.selected-tab {
  background-color: #409eff;
  color: white;
}
.empty-row {
  background-color: #f5f7fa;
  color: gray;
  text-align: center;
}
.label-text {
  width: 100px;
  font-weight: 500;
  color: #333;
  text-align: right;
  margin-right: 1rem;
  flex-shrink: 0;
}

.error-text {
  color: red;
  font-size: 12px;
  margin-left: 40px;
}

.input-error .el-input__inner {
  border-color: red !important;
}
</style>